package com.bai.websocketandmybatisplus.service.impl;

import cn.hutool.core.util.StrUtil;
import com.bai.websocketandmybatisplus.exception.AllErrorEnum;
import com.bai.websocketandmybatisplus.exception.MyException;
import com.bai.websocketandmybatisplus.mapper.UserMapper;
import com.bai.websocketandmybatisplus.model.User;
import com.bai.websocketandmybatisplus.service.IUserService;
import com.bai.websocketandmybatisplus.vo.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService implements IUserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public String add(User user) {
        if (user == null) {
            throw new MyException(AllErrorEnum.USER_IS_NULL); // 用户实体是空
        }
        int insert =userMapper.insert(user); // insert返回插入数据库的数量
        if (insert > 0) { // 大于0就是成功插入了
            //返回此次插入的用户id和用户名
            return user.getId() + user.getName();
        }
        throw new MyException(AllErrorEnum.ADDUSER_ERROR);
    }

    @Override
    public int deleteOne(String userId) {
        int delete = userMapper.deleteById(userId);
        // 同理，成功删除后返回影响的行数，验证是否成功删除
        if(delete>0){
            return delete;
        }
        throw new MyException(AllErrorEnum.DELETE_ERROR);
    }

    @Override
    public User updateByUserId(User user) {
        if (user == null) {
            throw new MyException(AllErrorEnum.USER_IS_NULL);
        }
        int update = userMapper.updateById(user);
        if (update > 0) {
            return user;
        }
        throw new MyException(AllErrorEnum.UPDATE_ERROR);
    }

    @Override
    public User detail(String userId) {
        if (StrUtil.isNotBlank(userId)) {
            return userMapper.selectById(userId);
        }
        throw new MyException(AllErrorEnum.USERID_IS_NULL);
    }

    @Override
    public PageVo<User> page(String userName, int pageNumber, int pageSize) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 判断包含用户名称查询条件, 将查询条件添加到queryWrapper里
        if(StrUtil.isNotBlank(userName)){ // 此方法用于检查传递的字符串是否不为空且不仅仅包含空白字符。
            // 添加模糊查询用户名条件
            queryWrapper.like("name",userName); //("数据库字段", 查询参数)
        }
        // 构建分页查询参数
        IPage<User> pageParam= new Page<>(pageNumber,pageSize);
        IPage<User> userIPage = userMapper.selectPage(pageParam, queryWrapper);
        return new PageVo<>(userIPage);
    }
}
